
let http_debug = false;
let log = function () {
    if(http_debug){
        console.log.call(console,...arguments);
    }
};

// get 请求
function get(url, params, callback){
    params = params || {};
    let dataStr = '';
    Object.keys(params).forEach(key => {
        dataStr += key + '=' + encodeURIComponent(params[key]) + '&';
    });
    if (dataStr !== '') {
        dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
        url = url + '?' + dataStr;
    }
    url = netApi.baseUrl + url;
    let xhr = cc.loader.getXMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.setRequestHeader("Content-Type","text/plain;charset=UTF-8");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            let response = xhr.responseText;
            log('response:',response);
            if (xhr.status >= 200 && xhr.status < 300) {
                callback(false, JSON.parse(response));
            }else{
                callback(true, response);
            }
        }
    };
    xhr.send();
}

//Post请求
function post(url, param, callback){
    param = param || {};
    url = netApi.baseUrl + url;
    let xhr = new XMLHttpRequest();
    let dataStr = '';
    Object.keys(param).forEach(key => {
        dataStr += key + '=' + encodeURIComponent(param[key])+ '&';
    });
    if (dataStr !== '') {
        dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
    }
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            let response = xhr.responseText;
            log('response:',response);
            if (xhr.status >= 200 && xhr.status < 300) {
                callback(false, JSON.parse(response));
            }else{
                callback(true, response);
            }
        }
    };
    xhr.send(dataStr);
}


let netApi = {
    baseUrl:'',
    apiVersion:-1,
    init(url,apiVersion){
        this.baseUrl = url;
        this.apiVersion = apiVersion;
    },
    user_login(obj,callback){
        post(this.apiUrl('user_login'),obj,callback);
    },

    user_create(obj,callback){
        post(this.apiUrl('user_create'),obj,callback);
    },

    item_query(obj,callback){
        post(this.apiUrl('item_query'),obj,callback);
    },

    item_delete(obj,callback){
        post(this.apiUrl('item_delete'),obj,callback);
    },

    item_add(obj,callback){
        post(this.apiUrl('item_add'),obj,callback);
    },

    apiUrl(p){
        return cc.path.join('api',`v${this.apiVersion}`,p);
    }
};

module.exports = netApi;
